<template>
    <div>
        <el-button  type="success"  @click="add" style="color: #FFF;" color="#3134C7" >
          新增
        </el-button>

  <el-table :data="tableData" style="width: 100%"  >
    <el-table-column fixed type="index" label="编号" width="60" />
    <el-table-column prop="userName" label="用户名" width="100" />
    <el-table-column prop="roleName" label="角色" width="150" />
    <el-table-column prop="sex" label="性别" width="60" >
        <template #default="scope">
            {{ scope.row.sex?'男':'女' }}
        </template>
    </el-table-column>
    <el-table-column prop="provinceName" label="所在省份" width="120" >
      <template #default="scope">
         {{ getProvinceName(scope.row.provinceName) }}
      </template>
    </el-table-column>
    <el-table-column prop="cityName" label="所在市" width="120" >
       <template #default="scope">
         {{ getCityName(scope.row.cityName) }}
      </template>
    </el-table-column>
    <el-table-column prop="regionName" label="所在县" width="120" >
       <template #default="scope">
         {{ getRegionName(scope.row.regionName) }}
      </template>
    </el-table-column>
     <el-table-column prop="addressDetail" label="地址详情" width="110" show-overflow-tooltip >
   <template #default="scope">
   {{ scope.row.addressDetail }}
  </template>

     </el-table-column>
      
    <el-table-column prop="creator" label="创建人" width="120" />
    <el-table-column prop="creatorDate" label="创建日期" width="200" >
         <template #default="scope">
            {{ moment(scope.row.creatorDate).format('yyyy-MM-DD HH:mm:ss') }}
        </template>
    </el-table-column>
    <el-table-column prop="updator" label="修改人" width="120" />

     <el-table-column prop="updatorDate" label="修改日期" width="200" >
        <template #default="scope" >
             <span v-if="!scope.row.updatorDate || scope.row.updatorDate === ''"> </span>
           <span v-else> {{ moment(scope.row.updatorDate).format('yyyy-MM-DD HH:mm:ss') }}</span>
        </template>
     </el-table-column>

    <el-table-column fixed="right" label="操作" min-width="180">
      <template #default="scope">
        <el-button  type="primary"  @click="update(scope.row)" plain>
          修改
        </el-button>
        <el-button  type="danger"  @click="del(scope.row.id)" plain>删除</el-button>
      </template>
    </el-table-column>
  </el-table>
    </div>

     <el-dialog v-model="dialogFormVisible" title="新增用户" width="1000">
<el-form
    ref="ruleFormRef"
    style="max-width: 600px"
    :model="ruleForm"
    :rules="rules"
    label-width="auto"
  >
    <el-form-item label="用户名：" prop="userName">
      <el-input v-model="ruleForm.userName" />
    </el-form-item>

    <el-form-item label="性别：" prop="sex">
      <el-radio-group v-model="ruleForm.sex">
        <el-radio :value="true">男</el-radio>
        <el-radio :value="false">女</el-radio>
      </el-radio-group>
    </el-form-item>

    <el-form-item label="所在地址：" prop="provinceId">



<el-select 
      v-model="ruleForm.provinceName" 
      placeholder="请选择省份" 
      @change="handleProvinceChange"
      style="width: 120px; margin-right: 8px;"
    >
      <el-option 
        v-for="item in provinceList" 
        :key="item.value" 
        :label="item.label" 
        :value="item.value"
      />
    </el-select>

    <!-- 城市选择（依赖省份） -->
    <el-select 
      v-model="ruleForm.cityName" 
      placeholder="请选择市" 
      @change="handleCityChange"
      style="width: 120px; margin-right: 8px;"
    >
      <el-option 
        v-for="item in cityList" 
        :key="item.value" 
        :label="item.label" 
        :value="item.value"
      />
    </el-select>

    <!-- 区县选择（依赖城市） -->
    <el-select 
      v-model="ruleForm.regionName" 
      placeholder="请选择县" 
      style="width: 120px;"
    >
      <el-option 
        v-for="item in districtList" 
        :key="item.value" 
        :label="item.label" 
        :value="item.value"
      />
    </el-select>
    </el-form-item>
     <el-form-item label="详细地址：" prop="addressDetail">
      <el-input v-model="ruleForm.addressDetail" />
    </el-form-item>

 <el-form-item label="部门" prop="region">
      <el-select v-model="ruleForm.departmentId" placeholder="请选择部门">
        <el-option label="IT信息部" value="1" />
        <el-option label="人力资源部" value="2" />
          <el-option label="财务部" value="3" />
        <el-option label="销售部" value="4" />
      </el-select>
    </el-form-item>

    <el-form-item>
      <el-button type="primary" @click="submitForm(ruleFormRef)">
        保存
      </el-button>
      <el-button @click="resetForm(ruleFormRef)">重置</el-button>
    </el-form-item>
  </el-form>
     </el-dialog>


     <el-dialog v-model="dialogFormVisibles" title="修改用户" width="1000">
<el-form
    ref="ruleFormRef"
    style="max-width: 600px"
    :model="ruleForm"
    :rules="rules"
    label-width="auto"
  >
    <el-form-item label="用户名：" prop="userName">
      <el-input v-model="ruleForm.userName" />
    </el-form-item>

   

    <el-form-item label="性别：" prop="sex">
      <el-radio-group v-model="ruleForm.sex">
        <el-radio :value="true">男</el-radio>
        <el-radio :value="false">女</el-radio>
      </el-radio-group>
    </el-form-item>

    <el-form-item label="所在地址：" prop="provinceId">
         
          <el-select 
      v-model="ruleForm.provinceName" 
      placeholder="请选择省份" 
      @change="handleProvinceChange"
      style="width: 120px; margin-right: 8px;"
    >
      <el-option 
        v-for="item in provinceList" 
        :key="item.value" 
        :label="item.label" 
        :value="item.value"
      />
    </el-select>

    <!-- 城市选择（依赖省份） -->
    <el-select 
      v-model="ruleForm.cityName" 
      placeholder="请选择市" 
      @change="handleCityChange"
      style="width: 120px; margin-right: 8px;"
    >
      <el-option 
        v-for="item in cityList" 
        :key="item.value" 
        :label="item.label" 
        :value="item.value"
      />
    </el-select>

    <!-- 区县选择（依赖城市） -->
    <el-select 
      v-model="ruleForm.regionName" 
      placeholder="请选择县" 
      style="width: 120px;"
    >
      <el-option 
        v-for="item in districtList" 
        :key="item.value" 
        :label="item.label" 
        :value="item.value"
      />
    </el-select>
         
     
    </el-form-item>
     <el-form-item label="详细地址：" prop="addressDetail">
      <el-input v-model="ruleForm.addressDetail" />
    </el-form-item>

    <el-form-item label="部门" prop="region">
      <el-select v-model="ruleForm.departmentId" placeholder="请选择部门">
        <el-option label="IT信息部" :value="1" />
        <el-option label="人力资源部" :value="2" />
        <el-option label="财务部" :value="3" />
        <el-option label="销售部" :value="4" />
      </el-select>
    </el-form-item>

    <el-form-item>
      <el-button type="primary" @click="submitForms(ruleFormRef)">
        保存
      </el-button>
      <el-button @click="reset">重置</el-button>
    </el-form-item>
  </el-form>
     </el-dialog>
</template>

<script lang="ts" setup>
import {useCounterStore} from '@/stores/counter'
const pinia=useCounterStore();
import axios from 'axios'
import {ref,reactive,onMounted, watch,nextTick} from 'vue'
import moment from 'moment'
const dialogFormVisible = ref(false)
const dialogFormVisibles = ref(false)
const tableData =ref([])
import Read from  '@/http/Readhttp'
import Write from '@/http/Writehttp'

onMounted(()=>{
getdata();
})
const getdata=()=>{
    Read.get("/api/Users/GetUser").then(res=>{
        console.log(res.data.data);
        
        tableData.value=res.data.datas
    })
}


//新增

const add=()=>{
    dialogFormVisible.value=true;
}
import { ElMessage,ElMessageBox, type FormInstance, type FormRules } from 'element-plus'
const ruleFormRef = ref<FormInstance>()
const ruleForm = reactive({
  id:'',
 "userName": "",
  "pwd": "12345678",
  "sex": true,
  "provinceName": "",
  "cityName": "",
  "regionName": "",
  "addressDetail": "",
  "updator":pinia.account.UserName,
  departmentId:''
})


const rules = reactive<FormRules>({
  addressDetail: [
    { required: true, message: '详细地址不能为空', trigger: 'blur' },
  ],
  userName: [
    { required: true, message: '用户名不能为空', trigger: 'blur' },
  ],
})

const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
        Write.post("/api/Users/AddUser",ruleForm).then(res=>{
            if(res.data.code==200)
        {
            ElMessage.success(res.data.msg);
            
            dialogFormVisible.value=false;
             ruleForm.addressDetail='';
            ruleForm.cityName='';
            ruleForm.provinceName='';
            ruleForm.regionName='';
            ruleForm.userName='';
            ruleForm.sex=false;
             ruleForm.departmentId='0'
            getdata();
        }
        else{
            ElMessage.error(res.data.msg);
        }
        })
      console.log('submit!')
    } else {
      console.log('error submit!', fields)
    }
  })
}

const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
}
const submitForms = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      ruleForm.updator=pinia.account.UserName;
        Write.put("/api/Users/UpdateUser",ruleForm).then(res=>{
            if(res.data.code==200)
        {
            ElMessage.success(res.data.msg);
            ruleForm.addressDetail='';
            ruleForm.cityName='';
            ruleForm.provinceName='';
            ruleForm.regionName='';
            ruleForm.userName='';
            ruleForm.departmentId='0'
            dialogFormVisibles.value=false;
            getdata();
        }
        else{
            ElMessage.error(res.data.msg);
        }
        })
      console.log('submit!')
    } else {
      console.log('error submit!', fields)
    }
  })
}

 

const update=(row:any)=>{
dialogFormVisibles.value=true;
ruleForm.addressDetail=row.addressDetail;
 ruleForm.id=row.id,
 ruleForm.userName=row.userName,
  ruleForm.pwd=row.pwd,
  ruleForm.sex=row.sex,
  ruleForm.provinceName=row.provinceName,
  ruleForm.departmentId=row.departmentId
// 先设置省份
  ruleForm.provinceName = row.provinceName;
  
  // 触发省份变化，加载城市列表
  handleProvinceChange(row.provinceName);
  
  // 设置城市（需要在城市列表加载完成后）
  nextTick(() => {
    ruleForm.cityName = row.cityName;
    
    // 触发城市变化，加载区县列表
    handleCityChange(row.cityName);
    
    // 设置区县（需要在区县列表加载完成后）
    nextTick(() => {
      ruleForm.regionName = row.regionName;
    });
  });

  
  ruleForm.addressDetail=row.addressDetail



}
const reset=()=>{
  ruleForm.cityName='';
ruleForm.regionName='';
ruleForm.addressDetail='';
ruleForm.provinceName='';
ruleForm.pwd='';
ruleForm.sex=false;
ruleForm.userName='';
ruleForm.updator='';
ruleForm.id=''
}
//删除
const del=(id:any)=>{
  ElMessageBox.confirm(
    '您确认删除吗?',
    '警告',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(() => {
      
      Write.put('/api/Users/DelUser',{id:id})
      .then(res=>{
        if(res.data.code==200){
          ElMessage.success(res.data.msg); 
          getdata();//重新加载数据
          }else{
            ElMessage.error(res.data.msg); 
          }

      });

    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '操作已被取消',
      })
    })
}


//省市县全国
import { regionData, codeToText } from 'element-china-area-data'

// 省份列表
const provinceList = regionData
// 城市列表
const cityList = ref<any[]>([])
// 区县列表
const districtList = ref<any[]>([])

// 省份改变时，加载对应城市
const handleProvinceChange = (provinceCode: string) => {
  ruleForm.cityName=''
  ruleForm.regionName=''

  
  const province = regionData.find(item => item.value === provinceCode)
  if (province && province.children) {
    cityList.value = province.children
  } else {
    cityList.value = []
  }
}

// 城市改变时，加载对应区县
const handleCityChange = (cityCode: string) => {
    ruleForm.regionName=''
  
  const province = regionData.find(item => item.value === ruleForm.provinceName)
  if (province) {
    const city = province.children?.find(item => item.value === cityCode)

    if (city?.children) {
      districtList.value = city.children
    } else {
      districtList.value = []
      console.warn('当前城市无区县数据')
    }
  }
}
console.log(regionData); 
// 监听 provinceId 变化，初始化城市列表
watch(()=>ruleForm.provinceName, (newVal) => {
  if (newVal) {
    handleProvinceChange(newVal)
  }
})

// 监听 cityId 变化，初始化区县列表
watch(()=>ruleForm.cityName, (newVal) => {
  if (newVal) {
    handleCityChange(newVal)
  }
})
// 编码转名称的工具函数
const getProvinceName = (code: string) => codeToText[code] || '--'
const getCityName = (code: string) => codeToText[code] || '--'
const getRegionName = (code: string) => codeToText[code] || '--'
</script>
<style scoped>
.text-truncate {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  max-width: 100%;
}
</style>